// components/getPhone/getPhone.js
import * as API_Member from '../../api/member'
import * as API_Config from '../../api/sysConfig'


Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    code:'',
    disabled:true,
    showDialog:true,
    timmer:''
  },

  lifetimes:{
    attached(){
      let that = this
      API_Config.getValueByKey("member_avatar").then(res =>{
        if('Y' == res){
          that.startCheck()
        }
      })
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    startCheck(){
      let that = this
      wx.login({
        success(res){
          that.setData({
            code:res.code,
            disabled:false
          })
        }
      })
      let token = wx.getStorageSync('token')
      //当没有的时候设置定时器等待token返回
      if(!token){
        clearInterval(this.data.timmer)
        this.data.timmer= setInterval(
          function () {
            wx.showLoading({
              title: '加载中...',
              mask:true
            })
            let d = wx.getStorageSync('token')
            if(d){
              wx.hideLoading()
              that.check()
            }
          }, 500);
      }else{
        that.check()
      }
    },
    check(){
      clearInterval(this.data.timmer)
      const member = wx.getStorageSync('member')
      if(!member.phone){
        wx.hideTabBar()
        this.setData({
          showDialog:false
        })
        getApp().globalData.phone = true
        // API_Member.reload(res =>{
        //   if(!res.phone){
        //     wx.hideTabBar()
        //      this.setData({
        //        showDialog:false
        //      })
        //    }
        // })
      }
      
    },
    getPhone (e) {
      let that = this
      getApp().globalData.phone = true
      this.setData({
          disabled:true 
      })
      if(e.detail.iv && e.detail.encryptedData){
        const params = {encryptedData:e.detail.encryptedData,iv:e.detail.iv,code:this.data.code}
        API_Member.flushPhone(params).then(res =>{
          if(res.success || res.exist ){
            wx.setStorageSync('member', res.member)
            wx.setStorageSync('token', res.token)
            this.setData({showDialog:true})
            wx.showTabBar({
              animation: true,
            })
          }
        })
      }else{
        wx.login({
          success(res){
            that.setData({
              code:res.code,
              disabled:false
            })
          }
        })
      }
    // API_Member.register(ed.detail.encryptedData)
  }
  }
})
